public class TestHeap {
    private int[] elem;
    private int usedSize;
    public TestHeap(){
        this.elem = new int[10];
    }
    public void initHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void creatHeap(){
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    private void shiftDown(int parent, int usedSize) {
        int child = 2*parent + 1;
        while (child < usedSize){
            if (child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
                //child一定是左右孩子最大值的下标
            if (elem[child] > elem[parent]){
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                //本身已经是大根堆了
                break;
            }
        }
    }
    private void swap(int i,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
}

